# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import os

from scrapy.utils.project import get_project_settings

from baidusolu.tool import get_today_filename, get_sql
import pymysql.cursors

class BaidusoluPipeline(object):

    def __init__(self):

        setting = get_project_settings()
        self.connection = pymysql.connect(
            host=setting.get('MYSQL_HOST'),#数据库地址
            port=setting.get('MYSQL_POST'),# 数据库端口
            db=setting.get('MYSQL_DB'), # 数据库名
            user = setting.get('MYSQL_USER'), # 数据库用户名
            password=setting.get('MYSQL_PASSWORD'), # 数据库密码
            charset=setting.get('MYSQL_CHARSET'), # 编码方式
            use_unicode=True,
            cursorclass=pymysql.cursors.DictCursor
        )

        self.cursor = self.connection.cursor()

        # filename = get_sql()
        # if os.path.exists(filename):
        #     open(filename, 'w').close()
        # self.f = open(filename, 'a')

    def process_item(self, item, spider):
        # query = (
        #                 "INSERT INTO sp_post_include (`type`, `post_id`, `is_included`, `included_page_num`, `label`, `status`) VALUES (%d, %d, %d, %d, %s, %d) ON DUPLICATE KEY UPDATE `is_included` = " + str(
        #             item['is_included']) + ';'
        #         ) % (
        #             int(item['type']),
        #             int(item['post_id']),
        #             int(item['is_included']),
        #             int(item['included_page_num']),
        #             item['label'],
        #             int(item['status']),
        #         )
        # self.f.write(query)
        # self.f.write('\n')

        query = "INSERT INTO sp_post_include (`type`, `post_id`, `is_included`, `included_page_num`, `label`, `status`) VALUES (%s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE `is_included` = " + str(
            item['is_included']) + ';'

        self.cursor.execute(query, (
            item['type'],
            item['post_id'],
            item['is_included'],
            item['included_page_num'],
            item['label'],
            item['status'],
        ))

        return item

    def close_spider(self, spider):
        # self.f.close()
        self.connection.commit()
        self.cursor.close()
        self.connection.close()
        pass
